/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.bayu.graph;

import com.bayu.common.lib.CommonUtil;
import com.bayu.controller.MainController;
import com.bayu.services.dao.AverageMouldingDao;
import com.bayu.services.dao.AvgMouldingDao;
import com.bayu.services.entity.AverageMoulding;
import com.bayu.services.entity.AvgMoulding;
import java.awt.Color;
import java.io.OutputStream;
import java.util.List;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.AxisLocation;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.DatasetRenderingOrder;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.TextAnchor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 *
 * @author Bayu
 */
@Controller
public class TPSMouldPMS {
    private String query;
    AverageMouldingDao averageMouldingDao;
    AvgMouldingDao avgMouldingDao;

    @Autowired
    public void setAverageMouldingDao(AverageMouldingDao averageMouldingDao){
      this.averageMouldingDao = averageMouldingDao;
    }

    @Autowired
    public void setAvgMouldingDao(AvgMouldingDao avgMouldingDao){
        this.avgMouldingDao = avgMouldingDao;
    }

    @RequestMapping("/tps-mould-pms-graph.png")
    public void averageMouldingGraph (OutputStream stream) throws Exception{
        JFreeChart chart = getChart();
        ChartUtilities.writeChartAsPNG(stream, chart, 1480,800);
    }

    private JFreeChart getChart() {
        DefaultCategoryDataset dataset1 = getDataset();
        String title="Grafik Pencapaian  Productivity TPS Model Line\r\nLine PMS";
        String tgl1="";
        String tgl2="";


      if(!MainController.startDate.equals("")){
          tgl1 = CommonUtil.formatStringDate(MainController.startDate);
          tgl2 = CommonUtil.formatStringDate(MainController.endDate);
          title = title+"\r\n"+ tgl1+"-"+tgl2;
      }
       final JFreeChart chart = ChartFactory.createBarChart(
            title,                      // chart title
           "Date",                      // domain axis label
           "Produktivitas kg/jam org(%)",                // range axis label
            dataset1,                   // data
            PlotOrientation.VERTICAL,
            true,                       // include legend
            true,                       // tooltips?
            false                       // URL generator?  Not required...
        );
        chart.setBackgroundPaint(new Color(204, 255, 204));
        CategoryPlot plot = chart.getCategoryPlot();

        plot.setDomainAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
        plot.setRangeAxisLocation(AxisLocation.TOP_OR_LEFT);

        CategoryItemRenderer renderer = plot.getRenderer();
        renderer.setSeriesPaint(0, Color.green);
        renderer.setSeriesPaint(1, Color.orange);
        renderer.setSeriesPaint(2, Color.PINK);
        renderer.setSeriesPaint(3, Color.RED);
        renderer.setSeriesPaint(4, Color.MAGENTA);
        renderer.setSeriesPaint(5, Color.cyan);
         renderer.setSeriesPaint(6, Color.LIGHT_GRAY);
        //renderer.setSeriesPaint(0, Color.red);
        //renderer.setBaseNegativeItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.INSIDE12, TextAnchor.TOP_CENTER));
        //renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        //renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER));
        //renderer.setBaseItemLabelsVisible(true);

        DefaultCategoryDataset dataset2 = getDataset2();

        plot.setDataset(1,dataset2);
        CategoryItemRenderer renderer2 = new LineAndShapeRenderer();

        renderer2.setSeriesPaint(0, Color.blue);
        //renderer2.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        //renderer2.setBaseItemLabelsVisible(true);
        plot.setRenderer(1, renderer2);

        plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);

        NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
        rangeAxis.setAutoRange(true);
//        rangeAxis.setRange(0, max);
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

        return chart;
    }

     public DefaultCategoryDataset getDataset(){

        DefaultCategoryDataset data1 = new DefaultCategoryDataset();
        //List dataAvg = this.averageMouldingDao.getAllByDate(MainController.startDate, MainController.endDate);
        List data = this.avgMouldingDao.getAllByDate2(MainController.startDate, MainController.endDate,"mouldpms");
        int avgStartMonth=0;
        int avgEndMonth=0;
        String avgStartDate="";
        String avgEndDate="";


        String tempDate[] = MainController.startDate.split("-");
        if((Integer.parseInt(tempDate[1]) - 3) <=0){
           if ((Integer.parseInt(tempDate[1])-3) == 0){

                avgEndMonth = Integer.parseInt(tempDate[1]);
                avgEndDate = tempDate[0]+"-"+avgEndMonth+"-"+tempDate[2];
                tempDate[0] = String.valueOf(Integer.parseInt(tempDate[0])-1);
                tempDate[1] = "12";
                avgStartMonth = Integer.parseInt(tempDate[1]);
                avgStartDate = tempDate[0]+"-"+avgStartMonth+"-"+tempDate[2];

           }
           else if ((Integer.parseInt(tempDate[1])-3) == -1){
               avgEndMonth = Integer.parseInt(tempDate[1]);
                avgEndDate = tempDate[0]+"-"+avgEndMonth+"-"+tempDate[2];
                tempDate[0] = String.valueOf(Integer.parseInt(tempDate[0])-1);
                tempDate[1] = "11";
                avgStartMonth = Integer.parseInt(tempDate[1]);
                avgStartDate = tempDate[0]+"-"+avgStartMonth+"-"+tempDate[2];
               System.out.println("bulan=-1");
           }
           else if ((Integer.parseInt(tempDate[1])-3) == -2){
               avgEndMonth = Integer.parseInt(tempDate[1]);
                avgEndDate = tempDate[0]+"-"+avgEndMonth+"-"+tempDate[2];
                tempDate[0] = String.valueOf(Integer.parseInt(tempDate[0])-1);
                tempDate[1] = "10";
                avgStartMonth = Integer.parseInt(tempDate[1]);
                avgStartDate = tempDate[0]+"-"+avgStartMonth+"-"+tempDate[2];
               System.out.println("bulan=-2");
           }

        }
        else{
            avgStartMonth= Integer.parseInt(tempDate[1]) - 3;
            avgEndMonth = Integer.parseInt(tempDate[1]);
            avgStartDate = tempDate[0]+"-"+avgStartMonth+"-"+tempDate[2];
            avgEndDate = tempDate[0]+"-"+avgEndMonth+"-"+tempDate[2];
        }
        List data2 = this.averageMouldingDao.getAllByDate2(avgStartDate,avgEndDate,"mouldpms");

        for(int i=0; i<data2.size(); i++){
            AverageMoulding am = (AverageMoulding)data2.get(i);
            String cat[] = am.getDate().toString().split("-");
            String avgMonthName = CommonUtil.getShortMonthName(Integer.parseInt(cat[1])-1);

            data1.addValue(am.getA(), "a", "avg "+avgMonthName);
            data1.addValue(am.getB(), "b", "avg "+avgMonthName);
            data1.addValue(am.getC(), "c", "avg "+avgMonthName);
            data1.addValue(am.getD(), "d", "avg "+avgMonthName);
            data1.addValue(am.getE(), "e", "avg "+avgMonthName);
            data1.addValue(am.getF(), "f", "avg "+avgMonthName);
            data1.addValue(am.getF(), "g", "avg "+avgMonthName);


        }

        for(int i=0;i<data.size();i++){
            AvgMoulding am = (AvgMoulding)data.get(i);
            String cat[] = am.getDate().toString().split("-");
            data1.addValue(am.getA(), "a", cat[2]);
            data1.addValue(am.getB(), "b", cat[2]);
            data1.addValue(am.getC(), "c", cat[2]);
            data1.addValue(am.getD(), "d", cat[2]);
            data1.addValue(am.getE(), "e", cat[2]);
            data1.addValue(am.getF(), "f", cat[2]);
            data1.addValue(am.getG(), "g", cat[2]);

        }
        return data1;
    }

    public DefaultCategoryDataset getDataset2(){
        DefaultCategoryDataset data1 = new DefaultCategoryDataset();
        //List dataAvg = this.averageMouldingDao.getAllByDate(MainController.startDate, MainController.endDate);
        List data = this.avgMouldingDao.getAllByDate2(MainController.startDate, MainController.endDate,"mouldpms");
        //List data = this.rejectCastingDao.getAllByDate("2010-12-01", "2010-12-31");

//        String tempDate[] = MainController.endDate.split("-");
//        int avgStartMonth = Integer.parseInt(tempDate[1]) - 3;
//        int avgEndMonth = Integer.parseInt(tempDate[1]);
//        String avgStartDate = tempDate[0]+"-"+avgStartMonth+"-"+tempDate[2];
//        String avgEndDate = tempDate[0]+"-"+avgEndMonth+"-"+tempDate[2];

        int avgStartMonth=0;
        int avgEndMonth=0;
        String avgStartDate="";
        String avgEndDate="";


        String tempDate[] = MainController.startDate.split("-");
        if((Integer.parseInt(tempDate[1]) - 3) <=0){
           if ((Integer.parseInt(tempDate[1])-3) == 0){

                avgEndMonth = Integer.parseInt(tempDate[1]);
                avgEndDate = tempDate[0]+"-"+avgEndMonth+"-"+tempDate[2];
                tempDate[0] = String.valueOf(Integer.parseInt(tempDate[0])-1);
                tempDate[1] = "12";
                avgStartMonth = Integer.parseInt(tempDate[1]);
                avgStartDate = tempDate[0]+"-"+avgStartMonth+"-"+tempDate[2];

           }
           else if ((Integer.parseInt(tempDate[1])-3) == -1){
               avgEndMonth = Integer.parseInt(tempDate[1]);
                avgEndDate = tempDate[0]+"-"+avgEndMonth+"-"+tempDate[2];
                tempDate[0] = String.valueOf(Integer.parseInt(tempDate[0])-1);
                tempDate[1] = "11";
                avgStartMonth = Integer.parseInt(tempDate[1]);
                avgStartDate = tempDate[0]+"-"+avgStartMonth+"-"+tempDate[2];
               System.out.println("bulan=-1");
           }
           else if ((Integer.parseInt(tempDate[1])-3) == -2){
               avgEndMonth = Integer.parseInt(tempDate[1]);
                avgEndDate = tempDate[0]+"-"+avgEndMonth+"-"+tempDate[2];
                tempDate[0] = String.valueOf(Integer.parseInt(tempDate[0])-1);
                tempDate[1] = "10";
                avgStartMonth = Integer.parseInt(tempDate[1]);
                avgStartDate = tempDate[0]+"-"+avgStartMonth+"-"+tempDate[2];
               System.out.println("bulan=-2");
           }

        }
        else{
            avgStartMonth= Integer.parseInt(tempDate[1]) - 3;
            avgEndMonth = Integer.parseInt(tempDate[1]);
            avgStartDate = tempDate[0]+"-"+avgStartMonth+"-"+tempDate[2];
            avgEndDate = tempDate[0]+"-"+avgEndMonth+"-"+tempDate[2];
        }

        List data2 = this.averageMouldingDao.getAllByDate2(avgStartDate,avgEndDate,"mouldpms");

        Double average;
        for(int i=0;i<data2.size();i++){
          AverageMoulding am = (AverageMoulding)data2.get(i);
          String cat[] = am.getDate().toString().split("-");
          String avgMonthName = CommonUtil.getShortMonthName(Integer.parseInt(cat[1])-1);
          //average = (am.getA()+am.getB()+am.getC()+am.getD()+am.getE())/5;
          //data1.addValue(am.getF(), "f", "avg " +avgMonthName);
          data1.addValue(am.getH(), "h", "avg " +avgMonthName);


        }

        //System.out.println("Start End "+MainController.startDate + MainController.endDate);
        for(int i=0; i<data.size(); i++){
             AvgMoulding am = (AvgMoulding)data.get(i);
             String cat[] = am.getDate().toString().split("-");
             //average = (am.getA()+am.getB()+am.getC()+am.getD()+am.getE())/5;
             //data1.addValue(am.getF(), "f", cat[2]);
             data1.addValue(am.getH(), "h", cat[2]);


        }

        return data1;
    }
}
